package com.alm.token.ui.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.GlideApp;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.base.BaseAdapter;
import com.alm.token.common.RefreshLoadMoreManager;
import com.alm.token.ui.data.bean.AddSubscribeOrderData;
import com.alm.token.ui.data.bean.CancelSubScribeOrderData;
import com.alm.token.ui.data.bean.DrawIndexData;
import com.alm.token.ui.data.bean.EggRankingData;
import com.alm.token.ui.data.bean.EggWalletLogData;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.data.bean.StakingOrderHistoryData;
import com.alm.token.ui.data.bean.SubscribeOrderListData;
import com.alm.token.ui.data.bean.SuperColorEggData;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.SubscribleOrderEggView;
import com.alm.token.ui.view.SuperColorEggView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.DateUtils;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.utils.LogUtil;
import com.alm.token.widget.DateTimePicker;
import com.alm.token.widget.FullyLinearLayoutManager;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.common.LineConfig;

import static com.alm.token.ui.activity.FundArealistActivity.INTENT_RESULT_INTO_CODE;
import static com.alm.token.ui.persenter.MyPreenter.draw;

public class SubscribeOrderEggActivity extends BaseActivity implements SubscribleOrderEggView<Object> {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.tv_clickreload)
    TextView tvClickreload;
    @BindView(R.id.nodatashow_body)
    RelativeLayout nodatashowBody;
    //    @BindView(R.id.fab_top)
//    SuspensionFab fab_top;
    @BindView(R.id.btn_addorder)
    Button btn_addorder;

    private List<SuperColorEggData.DataBean.EggGoodsBean> eggGoodsBeans = new ArrayList<>();

    private List<SubscribeOrderListData.DataBean.ListBean> dataBeanList = new ArrayList<>();
    private RefreshLoadMoreManager<SubscribeOrderListData.DataBean.ListBean> manager;
    private String limit = "100", page = "1";
    private String dateTime = "";

    @Override
    protected MyPreenter initPreenter() {
        return preenter = new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_subscribeorder_egg;
    }

    @Override
    protected void initVariables() {
        eggGoodsBeans = (List<SuperColorEggData.DataBean.EggGoodsBean>) getIntent().getSerializableExtra("eggGoodsBeans");
    }

    @Override
    protected void initViews() {
        new ActionBarHelper(this).setTitle(getString(R.string.superegg_hint_subscribe));
        initManager();
        recyclerView.setVisibility(View.GONE);
        nodatashowBody.setVisibility(View.VISIBLE);
        swipeRefreshLayout.setVisibility(View.GONE);
//        fab_top.setFabClickListener(this);
        btn_addorder.setOnClickListener(this);
    }


    private void initManager() {
        IncomeAdapter adapter = new IncomeAdapter(this);
        manager = new RefreshLoadMoreManager.Builder(this)
                .setAdapter(adapter)
                .setRecyclerView(recyclerView)
                .setLayoutManager(new FullyLinearLayoutManager(this))
                .setOnListItemClickListener(new RefreshLoadMoreManager.OnListItemClickListener() {
                    @Override
                    public void onListItemClick(BaseAdapter.BaseItem item, int position) {

                    }
                })
                .setSwipeRefreshLayout(swipeRefreshLayout)
                .setOnRefreshListener(new RefreshLoadMoreManager.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        swipeRefreshLayout.setRefreshing(false);
                        loadData();
                    }
                })
                .setOpenLoadMore(true)
                .setOnLoadMoreListener(new RefreshLoadMoreManager.OnLoadMoreListener() {
                    @Override
                    public void onLoadMore() {
                        manager.getAdapter().loadMoreEnd(true);
                        manager.getAdapter().loadMoreFail();
                        preenter.getSubscribeOrderList(limit, page);
                    }
                })
                .build();
        recyclerView.setNestedScrollingEnabled(false);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });
    }

    @Override
    protected void loadData() {
        limit = "100";
        page = "1";
        preenter.getSubscribeOrderList(limit, page);
    }

    protected void deletListener(int id) {
        DialogUtils.enterPayPsw(this, (pwd1) -> {
            preenter.getCancelSubScribeOrder(String.valueOf(id), pwd1);
        });
    }

    protected void submitListener(int id) {
        DialogUtils.enterPayPsw(this, (pwd1) -> {
//            long timeStampSec = System.currentTimeMillis()/1000;
//            String subTimestamp = String.format("%010d", timeStampSec);

            String subTimestamp = DateUtils.data(dateTime);
            preenter.getAddSubscribeOrder(String.valueOf(id), dateTime, pwd1, subTimestamp);
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_addorder:
//                showToast("11");
                onYearMonthDayTimePicker();
                break;
        }
    }

    public void onYearMonthDayTimePicker() {

        DateTimePicker picker = new DateTimePicker(this, DateTimePicker.HOUR_24);


        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        int second = c.get(Calendar.SECOND);
        if (minute + 5 <= 59) {
            minute += 5;
        }

//        LogUtil.d("hour="+hour);

        picker.setActionButtonTop(true);
        picker.setDateRangeStart(year - 5, 1, 1);
        picker.setDateRangeEnd(year + 5, 12, 31);
        picker.setSelectedItem(year, month + 1, day, hour, minute, second);
        picker.setTimeRangeStart(0, 0, 0);
        picker.setTimeRangeEnd(23, 59, 0);
        picker.setCanLinkage(false);
        picker.setCancelText(getString(R.string.common_cancel));
        picker.setTitleText(getString(R.string.superegg_hint_subscribe_pleasselect));
        picker.setSubmitText(getString(R.string.common_ok));
//        picker.setStepMinute(5);
        picker.setWeightEnable(true);
        picker.setWheelModeEnable(true);
        LineConfig config = new LineConfig();
        config.setColor(Color.BLUE);//线颜色
        config.setAlpha(120);//线透明度
        config.setVisible(true);//线不显示 默认显示
        picker.setLineConfig(config);
        picker.setLabel(getString(R.string.common_year),
                getString(R.string.common_month),
                getString(R.string.common_day),
                getString(R.string.common_hour),
                getString(R.string.common_minute),
                getString(R.string.common_second));
        picker.setOnDateTimePickListener(new DateTimePicker.OnYearMonthDayTimePickListener() {
            @Override
            public void onDateTimePicked(String year, String month, String day, String hour, String minute, String second) {
//                showToast(year + "-" + month + "-" + day + " " + hour + ":" + minute + ":"+second);
                dateTime = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
                showPopwindow();
            }
        });
        picker.show();
    }

    @Override
    public void getData(Object o) {

    }

    private boolean isfull = false;
    private List<SubscribeOrderListData.DataBean.ListBean> dataBeanListold = new ArrayList<>();

    @Override
    public void getSubscribeOrderList(SubscribeOrderListData subscribeOrderListData) {
        if (subscribeOrderListData.getStatus() == 0) {

//            List<SubscribeOrderListData.DataBean.ListBean> listBeans1 = new ArrayList<>();
//            SubscribeOrderListData.DataBean.ListBean listBean = new SubscribeOrderListData.DataBean.ListBean();
//            listBean.setId(1);
//            listBean.setPayMio(1000.0000);
//            listBean.setStatus(0);// 0 待支付 1 等待中 2 成功 3 退回
//            listBean.setSubscribeTime("2019-10-10 10:10:10");
//            listBeans1.add(listBean);
//            subscribeOrderListData.getData().setList(listBeans1);


            if (EmptyUtils.isNotEmpty(subscribeOrderListData.getData()) &&
                    EmptyUtils.isNotEmpty(subscribeOrderListData.getData().getList())) {
                List<SubscribeOrderListData.DataBean.ListBean> list = subscribeOrderListData.getData().getList();

                if (Integer.valueOf(page) == 1) {
                    dataBeanList.clear();
                } else if (!isfull && dataBeanList.size() > (Integer.valueOf(page) - 1) * 100) {
                    dataBeanList.removeAll(dataBeanListold);
                }
//            dataBeanList.clear();
                if (list.size() == 100) {
                    isfull = true;
                    page = String.valueOf(Integer.valueOf(page) + 1);
                } else {
                    isfull = false;
                }

                dataBeanListold = list;
                for (int i = 0; i < dataBeanListold.size(); i++) {
                    dataBeanListold.get(i).setLayoutId(IncomeAdapter.LAYOUT_ID);
                }
                dataBeanList.addAll(dataBeanListold);
                manager.setData(dataBeanList);
            } else {
                dataBeanList.clear();
                dataBeanListold.clear();
                manager.setData(dataBeanList);
            }

        } else {
            showToast(subscribeOrderListData.getMsg());
        }

        if (dataBeanList.size() == 0) {
            swipeRefreshLayout.setVisibility(View.GONE);
            recyclerView.setVisibility(View.GONE);
            nodatashowBody.setVisibility(View.VISIBLE);
        } else {
            nodatashowBody.setVisibility(View.GONE);
            swipeRefreshLayout.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void getAddSubscribeOrder(AddSubscribeOrderData addSubscribeOrderData) {
        showToast(addSubscribeOrderData.getMsg());
        if (addSubscribeOrderData.getStatus() == 0) {
            loadData();
        }
    }

    @Override
    public void getCancelSubScribeOrder(CancelSubScribeOrderData cancelSubScribeOrderData) {
        showToast(cancelSubScribeOrderData.getMsg());
        if (cancelSubScribeOrderData.getStatus() == 0) {
            loadData();
        }
    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        } else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {
        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {
        showWaitDialog();
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.tv_clickreload)
    public void onViewClicked() {
        loadData();
    }

//    @OnClick({R.id.ly_ooutmoneybizhongtop, R.id.tv_buycommit})
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.ly_ooutmoneybizhongtop:
//
//                break;
//        }
//    }


    public class IncomeAdapter extends BaseAdapter<SubscribeOrderListData.DataBean.ListBean> {

        public static final int LAYOUT_ID = R.layout.item_subscribeorder;

        public IncomeAdapter(@NonNull Context context) {
            super(context);

        }

        @Override
        protected void convert(BaseViewHolder helper, SubscribeOrderListData.DataBean.ListBean dataBean, int itemType) {
            if (dataBean == null)
                return;
            /**
             * subscribeTime : 2019-10-10 10:10:10
             * payMio : 1000.0000
             * status : 1
             * id : 1
             */
            helper.setText(R.id.tv_channelType, getString(R.string.alphago_hint_paymoney) + ":" + CommonUtil.saveToPoint4WithNo(dataBean.getPayMio()));
            helper.setText(R.id.tv_createTime, dataBean.getSubscribeTime());
            // 0 待支付 1 等待中 2 成功 3 退回
            helper.setText(R.id.tv_staue,
                    dataBean.getStatus() == 0 ? getString(R.string.tv_hint_activity_order_staue_paywait)
                            : dataBean.getStatus() == 1 ? getString(R.string.superegg_hint_subscribe_staue_wait)
                            : dataBean.getStatus() == 2 ? getString(R.string.superegg_hint_subscribe_staue_succ)
                            : getString(R.string.superegg_hint_subscribe_staue_cancle));

            helper.setOnClickListener(R.id.btnDelete, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    showToast(dataBean.getId() + "     ");
                    deletListener(dataBean.getId());
                }
            });

////            ImageView icomImg = helper.getView(R.id.icon);
////            GlideApp.with(context).load(dataBean.getMoneyTypeIcon()).error(R.drawable.icon_arctic)
////                    .into(icomImg);
//
//            helper.setText(R.id.tv_channelType, dataBean.getChannelTypeName() + "");
//            helper.setText(R.id.tv_createTime, dataBean.getDate());//CommonUtil.getDateTimeFromMillisecond(dataBean.getUpdateTime() != 0 ? dataBean.getUpdateTime() : dataBean.getCreateTime())
//            double money = dataBean.getMoney();
//            if (money < 0) {
////                helper.setTextColor(R.id.tv_money, getResources().getColor(R.color.lehuobao_zhichu));
//                helper.setImageDrawable(R.id.icon, getResources().getDrawable(R.drawable.icom_outdown));
//                helper.setText(R.id.tv_money, CommonUtil.saveToPoint4WithNo(money));
//            } else {
//                helper.setTextColor(R.id.tv_money, getResources().getColor(R.color.colorgreen1));
//                helper.setImageDrawable(R.id.icon, getResources().getDrawable(R.drawable.icom_getup));
//                helper.setText(R.id.tv_money, "+" + CommonUtil.saveToPoint4WithNo(money));
//            }
        }

    }

    PopupWindow popWindow;

    private void showPopwindow() {
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.view_pop_selecter, null);
        LinearLayout ly_pop_body = popView.findViewById(R.id.ly_pop_body);

        if (EmptyUtils.isNotEmpty(eggGoodsBeans)) {
            for (int i = 0; i < eggGoodsBeans.size(); i++) {
                SuperColorEggData.DataBean.EggGoodsBean eggGoodsBean = eggGoodsBeans.get(i);

                /**
                 * id : 1
                 * name : 支付0.5
                 * remark :
                 * eth : 0.5
                 * cappingMultiple : 1.3
                 * getSeth : 0.5
                 * poolPro : 0.35
                 * createTime : 1557046377000
                 * updateTime : 1557198793000
                 * endTime : null
                 * status : 1
                 */


                View itemView = View.inflate(this, R.layout.item_pop_subscribeorder, null);
                ((TextView) itemView.findViewById(R.id.name)).setText(eggGoodsBean.getName());

                int finalI = i;
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        submitListener(eggGoodsBeans.get(finalI).getId());
                        popWindow.dismiss();
                    }
                });
                ly_pop_body.addView(itemView);
            }
            ly_pop_body.setBackgroundColor(getResources().getColor(R.color.text_cccccc));
        }

        RelativeLayout outside = popView.findViewById(R.id.pop_outside);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        if (popWindow == null) {
            popWindow = new PopupWindow(popView, width, height);
            popWindow.setAnimationStyle(R.style.BottomToTopAnim);
//        popWindow.setFocusable(true);
            popWindow.setOutsideTouchable(true);// 设置同意在外点击消失
        }
        outside.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });

        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }
}
